package com.up.widgets;

import java.net.MalformedURLException;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.up.demo.R;
import com.up.utils.ImageThreadLoader;
import com.up.utils.ImageThreadLoader.ImageLoadedListener;

public class ExAdapter extends ArrayAdapter<Map<String,?>>{
	
	private Context context;
	private LayoutInflater inflater;
	private int resId=0; 
	private ImageThreadLoader imageLoader;
	private List<Map<String,?>> listitem;
	
	public ExAdapter(Context context, int resId, List<Map<String,?>> dataList){
		super(context, 0, dataList);
		this.resId = resId;
		inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.context = context;
		this.listitem = dataList;
		this.imageLoader = new ImageThreadLoader(context);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view;
		TextView title;
		final ImageView image;
		
		view = inflater.inflate(resId, parent, false);
		
		try{
			title = (TextView)view.findViewById(R.id.text2);
			image = (ImageView)view.findViewById(R.id.icon);
		}catch(ClassCastException e){
			throw e;
		}
		Map<String,?> item = listitem.get(position);
		
		
		title.setText(Html.fromHtml(item.get("title").toString(),null,null));
		Bitmap cachedImage = null;
		
		try {
			
			cachedImage = imageLoader.loadImage(item.get("image").toString(), new ImageLoadedListener() {
				public void imageLoaded(Bitmap imageBitmap) {
					image.setImageBitmap(imageBitmap);
					// Let the list know data is changed
					notifyDataSetChanged();  
				}
			});
		}catch(MalformedURLException e){
		
		}
		
		if( cachedImage != null ) {
			image.setImageBitmap(cachedImage);
		}
		return view;
	}

}
